
#views.py
#this is the views file for sanjhachoolha

import os
import re
import datetime
import django
#import atom
import time
from google.appengine.api import mail
from google.appengine.api import users
from google.appengine.ext import db
from google.appengine.ext.db import djangoforms
#import gdata.service
#import gdata.alt.appengine
#import gdata.calendar.service


from django import http
from django import shortcuts
from django.http import HttpResponse, HttpResponseRedirect
from django.core.urlresolvers import reverse

from django import forms #will be changed in newer django 
from sanjhachoolha.models import * #change the format of this import
from django.utils.translation import gettext
from django.forms.util import ErrorList, ValidationError, smart_unicode
from django.contrib.syndication.feeds import Feed
from django.contrib.syndication.feeds import FeedDoesNotExist
from django.core.exceptions import ObjectDoesNotExist


#########Regexps begins
wordregex = "^[a-zA-Z0-9\\-\'\. ]+$"
emailregex = "^[a-zA-Z0-9\_\.]{3,}\@[a-zA-Z0-9\_\.]{3,}$"
####regexps ends


########utility functions begin

##"-".join(re.findall("\w+", " killer be @dam$$$ hell? ?"))
#user = users.get_current_user()
#sign_in = users.create_login_url("")
#sign_out= users.create_logout_url("")
    
####utility functions end


#########Classes Begin

class CSVField(forms.Field):
    def __init__(self, regex, max_length=None, min_length=None, error_message=None, *args, **kwargs):
        """
        regex can be either a string or a compiled regular expression object.
        error_message is an optional error message to use, if
        'Enter a valid value' is too generic for you.
        """
        super(CSVField, self).__init__(*args, **kwargs)
        if isinstance(regex, basestring):
            regex = re.compile(regex)
        self.regex = regex
        self.max_length, self.min_length = max_length, min_length
        self.error_message = error_message or gettext(u'Enter a valid value.')

    def clean(self, value):
        """
        Validates that the csv attributes matches the regular expression. Returns a
        Unicode object.
        """
        super(CSVField, self).clean(value)
        
        if value == u'':
            return value
        if self.max_length is not None and len(value) > self.max_length:
            raise ValidationError(gettext(u'Ensure this value has at most %d characters.') %
                                   self.max_length)
        if self.min_length is not None and len(value) < self.min_length:
            raise ValidationError(gettext(u'Ensure this value has at least %d characters.') %
                                   self.min_length)

        value = value.lower()
        value = list(set(re.split('^\s*|\s*,+\s*|\s*$', value)))
        if (value[0] == ''):
            value.remove('')
        for var in value:
            if not self.regex.search(var):
                raise ValidationError(self.error_message)
        return value
    
    
class Form1(forms.Form):
    category = CSVField('^[a-zA-Z0-9\\-\'\. ]+$', max_length=100)#csv field
    priority = forms.ChoiceField(widget=forms.RadioSelect, choices=(('low', 'Low'),
                                        ('medium', 'Medium'),
                                        ('high', 'High'),
                                        ('urgent', 'Urgent'),
                                        ))
    tags = CSVField(wordregex, max_length=100)#csv field
    skills = CSVField(wordregex, max_length=100)#csv field
    coordinators = CSVField(emailregex)#csv email field
    status = forms.ChoiceField(widget=forms.RadioSelect, choices=(('new', 'New'),
                                        ('assigned', 'Assigned'),
                                        ('closed', 'Closed'),
                                        ('modified', 'Modified'),
                                        ('verified', 'Verified'),
                                        ('deleted', 'Deleted'),
                                        ))
    def clean_coordinators(self):
        data = self.cleaned_data['coordinators']
#        raise error
        kl=[]
        for coordinator in data:
                c = SCUser.gql("WHERE email_id = :1",coordinator).get()
                
                if not c:
                    coord_error="we see %s is not a registerd scuser" % coordinator
                    raise forms.ValidationError(coord_error)
                else:                  
                   kl.append(c.key())
    
                   
        
        return kl


class Form2(djangoforms.ModelForm):
    class Meta:
        model = Acton
        fields=('title', 'description', 'eta', 'timeNeeded' )
        
        
class FormPost(djangoforms.ModelForm):
    class Meta:
        model = Post
        fields=('content')
        
class FormActor(forms.Form):
    skills= forms.CharField()
    how= forms.CharField(widget=forms.Textarea(attrs={'row':3,
                                                      'cols':50,
                                                      }), label="How I will Help")
    more=forms.CharField(widget=forms.Textarea(attrs={'row':3,
                                                      'cols':50,
                                                      }), initial="Anything else you want to mention...", required=False)
class SearchForm(forms.Form):
    title = forms.CharField(required=False)
                
class Contain():    
    deletable=None
    post=None

####Classes end


def respond(request, user, template, params=None):
  """Helper to render a response, passing standard stuff to the response.

  Args:
    request: The request object.
    user: The User object representing the current user; or None if nobody
      is logged in.
    template: The template name; '.html' is appended automatically.
    params: A dict giving the template parameters; modified in-place.

  Returns:
    Whatever render_to_response(template, params) returns.

  Raises:
    Whatever render_to_response(template, params) raises.
  """
  if params is None:
    params = {}
  if user:
    params['user'] = user
    params['sign_out'] = users.create_logout_url('/')
    params['is_admin'] = (users.is_current_user_admin() and
                          'Dev' in os.getenv('SERVER_SOFTWARE'))
  else:
    params['sign_in'] = users.create_login_url(request.path)
  if not template.endswith('.html'):
    template += '.html'
  return shortcuts.render_to_response(template, params)



def index(request):
    """show index"""
    signin_view="sanjhachoolha.views.index"
    signout_view="sanjhachoolha.views.index"
    ##put the code block below in a function
    
    user_ = users.get_current_user()
    sign_in = users.create_login_url(reverse(signin_view))
    if user_:
        var= SCUser.gql("WHERE email_id = :1", user_.email().lower()).get()
        if not var:
            
            var2 = user_.email()
            var2 = var2.lower()
            scuser=SCUser(user=user_, email_id = var2).put()
        sign_out=users.create_logout_url(reverse(signout_view))
        foo=sign_out
        login_message="Sign out"
    else:
        foo=sign_in
        login_message="Sign in"
        
    responseText = """Hello, world. This shows the main acton index. Please try the following\
     urls, based on\
    <a href="http://code.google.com/p/sanjhachoolha/wiki/URLPatterns"\
    target="_blank">http://code.google.com/p/sanjhachoolha/wiki/URLPatterns</a><br/>\
    For URLs with numbers (like 25 and 44), try changing them, and see what happens<br/>\
    <ul>\
    <li><a href="/sanjhachoolha/acton/add">/sanjhachoolha/acton/add</a></li>\
    <li><a href="/sanjhachoolha/acton/25">/sanjhachoolha/acton/25</a></li>\
      <li><a href="/sanjhachoolha/acton/25/edit">/sanjhachoolha/acton/25/edit</a></li>\
      <li><a href="/sanjhachoolha/acton/25/subscribe--POST request">/sanjhachoolha/acton/25/subscribe</a></li>\
      <li><a href="/sanjhachoolha/acton/25/unsubscribe--POST request">/sanjhachoolha/acton/25/unsubscribe</a></li>\
      <li><a href="/sanjhachoolha/acton/25/signup">/sanjhachoolha/acton/25/signup</a></li>\
      <li><a href="/sanjhachoolha/acton/25/leave">/sanjhachoolha/acton/25/leave</a></li>\
      <li><a href="/sanjhachoolha/acton/25/comments/add">/sanjhachoolha/acton/25/comments/add</a></li>\
      <li><a href="/sanjhachoolha/acton/25/comments/44/delete">/sanjhachoolha/acton/25/comments/44/delete</a></li>\
      <li><a href="/sanjhachoolha/search">/sanjhachoolha/search</a></li>\
      <li><a href="/sanjhachoolha/list">/sanjhachoolha/list</a></li>\
      <li><a href="/sanjhachoolha/listusers">/sanjhachoolha/listusers</a></li>\
      <li><a href="/sanjhachoolha/users/25">/sanjhachoolha/list</a></li>\
      <li><a href="/sanjhachoolha/feeds/latest/25">/sanjhachoolha/feeds/latest/25</a></li>
      <li><a href="/sanjhachoolha/list/category">/sanjhachoolha/list/category</a></li>
      <li><a href="/sanjhachoolha/list/category/catname">/sanjhachoolha/list/category/catName</a></li>
      </ul>\
      """
    return respond(request, None, 'sc-base', {'content': responseText,
                                              'foo':foo,
                                              'user_':user_,
                                              'login_message':login_message})

####add() begins  
def add(request):
    """add Acton to database  """
    signin_view="sanjhachoolha.views.add"
    signout_view="sanjhachoolha.views.add"
    ##put the code block below in a function
    scuser=None
    user_ = users.get_current_user()
    sign_in = users.create_login_url(reverse(signin_view))
    if user_:
        var= SCUser.gql("WHERE email_id = :1", user_.email().lower()).get()
        if var:
            if var.role=='ActonCreator':
                scuser=var.key()
            else:
                message=" aren't currently an ActonCreator"
                return shortcuts.render_to_response("sc-actonperm.html", {'var':var,
                                                                          'message':message,
                                                                          'foo': sign_in,
                                                                          'login_message':"Sign in" })
        else:
            var2 = user_.email()
            var2 = var2.lower()
            scuser=SCUser(user=user_, email_id = var2).put()
    else:
        
        return shortcuts.render_to_response("sc-login.html", {'foo': sign_in,
                                                              'login_message':"Sign in" })
         
    if request.method == 'POST': # If the form has been submitted...
        eform = Form2(request.POST) # A form bound to the POST data
        oform = Form1(request.POST)
        if oform.is_valid() and eform.is_valid(): # All validation rules pass
            acton = eform.save(commit=False)
                        
            acton.creator = scuser
            
         
            var = Priority.gql("WHERE name=:1", oform.cleaned_data['priority']).get()
            if var:
                acton.priority = var.key()
            else:
                acton.priority = Priority(name=oform.cleaned_data['priority']).put()
                
                
            for category in oform.cleaned_data['category']:
                var = Category.gql("WHERE name=:1", category ).get()
                if var:
                    acton.category.append(var.key())
                else:
                    c = Category(name=category)
                    acton.category.append(c.put())  # docs/datastore/functions#put()
                      
            for tag in oform.cleaned_data['tags']:
                var = Tags.gql("WHERE name=:1", tag ).get()
                if var:
                    acton.tags.append(var.key())
                else:
                    c = Tags(name=tag)
                    acton.tags.append(c.put())                

            for skill in oform.cleaned_data['skills']:
                var = Skills.gql("WHERE name=:1", skill ).get()
                if var:
                    acton.skills.append(var.key())
                else:
                    c = Skills(name=skill)
                    acton.skills.append(c.put())
            
            for coordinator in oform.cleaned_data['coordinators']:
                acton.coordinators.append(coordinator)
            
            var = Status.gql("WHERE name=:1", oform.cleaned_data['status']).get()
            if var:
                acton.status = var.key()
            else:
                acton.status = Status(name=oform.cleaned_data['status']).put()
            
            acton.slug = "-".join(re.findall("\w+", acton.title))
            acton_id = acton.put().id()
            
            

            return HttpResponseRedirect(reverse('sanjhachoolha.views.show',
                                                 kwargs= {'slug': acton.slug,
                                                          'acton_id':acton_id,
                                                        }
                                                 ))

    else:
        eform = Form2(initial = {"title":"Enter title",
                                 "eta": "mm/dd/yyyy hh:mm",
                                 "timeNeeded": "hh:mm",
                                 "description": "Description of your acton" })
        oform= Form1() # An unbound form
        
    
    
    sign_out=users.create_logout_url(reverse(signout_view))#wether to allow signout must be views'decision 
    return shortcuts.render_to_response('sc-actonform.html', {'eform': eform,
                                                              'oform':oform,
                                                              'login_message':"Sign out",
                                                              'foo':sign_out, 
                                                              'user_':user_,                                                              
                                                            })
      
def show(request, acton_id, slug=None):
    """show acton with with acton_id"""
    
    
    signin_view="sanjhachoolha.views.show"
    signout_view="sanjhachoolha.views.show"
    ##put the code block below in a function
    scuser=None
    user_ = users.get_current_user()
    if user_:
        var= SCUser.gql("WHERE email_id = :1", user_.email().lower()).get()
        if var:
            scuser=var.key()
        else:
            scuser=SCUser(user=user_, email_id=user_.email().lower()).put()
        foo=users.create_logout_url(reverse(signout_view, kwargs={'acton_id':acton_id,
                                                                      'slug':slug,}))
        message="Sign out"
    else:
        foo = users.create_login_url(reverse(signin_view, kwargs={'acton_id':acton_id,
                                                                      'slug':slug,}))
        message="Sign in"
        


    acton = Acton.get_by_id(int(acton_id))
    CSV=[]
    
    categories=[]
    for categoryKey in acton.category:
        category = Category.get(categoryKey)
        categories.append(category.name)
    CSV.append(categories)
    
    tags=[]
    for tagKey in acton.tags:
        tag = Tags.get(tagKey)
        tags.append(tag.name)
    CSV.append(tags)
        
    skills=[]
    for skillKey in acton.skills:
        skill = Skills.get(skillKey)
        skills.append(skill.name)
    CSV.append(skills)
    
    coordinators=[]
    for coordinatorKey in acton.coordinators:
        coordinator = SCUser.get(coordinatorKey)
        coordinators.append(coordinator.user.nickname())
    CSV.append(coordinators)    
    
    actors=[]
    for actorKey in acton.actors:
        actor = SCUser.get(actorKey)
        actors.append(actor.user.nickname())
    CSV.append(actors)
    
    
    pform = FormPost()    
    
    if scuser in acton.subscribers:
        subscribed=True
    else:
        subscribed=False
    
    if scuser in acton.actors:
        acting=True
    else:
        acting=False
    
    
    
    
    posts=[]
    for post in acton.post_set.order('-timestamp').fetch(5):
        container= Contain()
        if user_:
            if (user_.email().lower()==post.poster.email_id or
                 user_.email().lower()==acton.creator.email_id) and post.deleted==False:
                container.post=post
                container.deletable=True
                
            else:
                container.post=post
                container.deletable=False
        else:
            
            container.post=post
            container.deletable=False
        
        posts.append(container)
    
    
    return shortcuts.render_to_response('sc-actonshow.html', {'pform':pform,
                                                              'acton':acton,
                                                              'posts':posts,
                                                              'user_': user_,
                                                              'acting':acting,
                                                              'foo':foo,
                                                              'scuser':scuser,                                                             
                                                              'CSV':CSV,
                                                              'subscribed':subscribed,
                                                              'login_message':message,
                                                              })
  


def edit(request, acton_id):
    """adds an acton"""
    signin_view="sanjhachoolha.views.edit"
    signout_view="sanjhachoolha.views.edit"
    ##put the code block below in a function
    scuser=None
    user_ = users.get_current_user()
    sign_in = users.create_login_url(reverse(signin_view, kwargs={'acton_id':acton_id}))
    if user_:
        var= SCUser.gql("WHERE email_id = :1", user_.email().lower()).get()
        if var:
            if var.role=='ActonCreator' or var.role=="Admin":
                scuser=var.key()
            else:
                message=" aren't currently an ActonCreator or admin"
                return shortcuts.render_to_response("sc-actonperm.html", {'var':var,
                                                                          'message':message,
                                                                          'foo': sign_in,
                                                                          'login_message':"Sign in" })
        else:
            var2 = user_.email()
            var2 = var2.lower()
            scuser=SCUser(user=user_, email_id = var2).put()
    else:
        
        return shortcuts.render_to_response("sc-login.html", {'foo': sign_in,
                                                              'login_message':"Sign in"})
    
    
    acton=Acton.get_by_id(int(acton_id))
    temp=acton#this is for diffing


    categories=[]
    for categoryKey in acton.category:
        category = Category.get(categoryKey)
        categories.append(category.name)
    lcategories=set(categories)
    categories=", ".join(categories)
    
    tags=[]
    for tagKey in acton.tags:
        tag = Tags.get(tagKey)
        tags.append(tag.name)
    ltags=set(tags)
    tags=", ".join(tags)
        
    skills=[]
    for skillKey in acton.skills:
        skill = Skills.get(skillKey)
        skills.append(skill.name)
    lskills=set(skills)
    skills=", ".join(skills)
    
    coordinators=[]
    for coordinatorKey in acton.coordinators:
        coordinator = SCUser.get(coordinatorKey)
        coordinators.append(coordinator.email_id)
    lcoordinators=set(coordinators)
    coordinators=", ".join(coordinators)
    
        
 
    
    
    
    if request.method == 'POST': # If the form has been submitted...
        eform = Form2(request.POST, instance=acton) # A form bound to the POST data
        oform = Form1(request.POST)
        if oform.is_valid() and eform.is_valid(): # All validation rules pass
            
            
            message=""" [Autogenerated] Acton Edited: <br /><table>
            <tr><th>Field</th><th>Was</th><th>Is</th>"""
            change="<tr><td>%s</td><td>%s</td><td>%s</td></tr>"
            if acton.title!=eform.cleaned_data['title']:
                var=change % ("Title", acton.title, eform.cleaned_data['title'])
                message += var                
            if acton.description!=eform.cleaned_data['description']:
                var=change % ("Description", acton.description, eform.cleaned_data['description'])
                message += var
            if acton.eta != eform.cleaned_data['eta']:
                var=change % ("ETA", acton.eta, eform.cleaned_data['eta'])
                message += var
            if acton.timeNeeded != eform.cleaned_data['timeNeeded']:
                var=change % ("TimeNeeded", acton.timeNeeded, eform.cleaned_data['timeNeeded'])
                message += var
            if acton.priority.name.lower()!= oform.cleaned_data['priority']:
                var=change % ("Priority", acton.priority.name, oform.cleaned_data['priority'].capitalize())
                message +=var
            if acton.status.name.lower()!= oform.cleaned_data['status']:
                var=change % ("Status", acton.status.name, oform.cleaned_data['status'].capitalize())
                message +=var
            message += "</table>"
            
            message2="<table><tr><th>field</th><th>Removed</th><th>added</th</tr>"
            change="<tr><td>%s</td><td>%s</td><td>%s</td</tr>"
            foo=set(oform.cleaned_data['skills'])
            if lskills != foo:
                var=change % ("Skills", ", ".join(lskills-foo), ", ".join(foo-lskills))
                message2 += var
            foo=set(oform.cleaned_data['category'])    
            if foo != lcategories:
                var=change % ("Categories", ", ".join(lcategories - foo), ", ".join(foo - lcategories))
                message2 += var
#            foo=set(oform.cleaned_data['coordinators'])
#            if foo != lcoordinators:
#                var=change % ("coordinators", lcoordinators - foo, foo - lcoordinators)
#                message2 += var
            foo=set(oform.cleaned_data['tags'])
            if foo != ltags:
                var=change % ("tags", ", ".join(ltags - foo), ", ".join(foo - ltags))
                message2 += var
            message2 += "</table>" 
            
            
            acton=eform.save(commit=False)      
         
                            
            var = Priority.gql("WHERE name=:1", oform.cleaned_data['priority']).get()
            if var:
                acton.priority = var.key()
            else:
                acton.priority = Priority(name=oform.cleaned_data['priority']).put()
                            
            
            acton.category=[]    
            for category in oform.cleaned_data['category']:
                var = Category.gql("WHERE name=:1", category ).get()
                if var:
                    acton.category.append(var.key())
                else:
                    c = Category(name=category)
                    acton.category.append(c.put())  # docs/datastore/functions#put()
                      
            acton.tags=[]
            for tag in oform.cleaned_data['tags']:
                var = Tags.gql("WHERE name=:1", tag ).get()
                if var:
                    acton.tags.append(var.key())
                else:
                    c = Tags(name=tag)
                    acton.tags.append(c.put())
                                    
            acton.skills=[]
            for skill in oform.cleaned_data['skills']:
                var = Skills.gql("WHERE name=:1", skill ).get()
                if var:
                    acton.skills.append(var.key())
                else:
                    c = Skills(name=skill)
                    acton.skills.append(c.put())
            
            acton.coordinators=[]
            for coordinator in oform.cleaned_data['coordinators']:
                acton.coordinators.append(coordinator)
            
            var = Status.gql("WHERE name=:1", oform.cleaned_data['status']).get()
            if var:
                acton.status = var.key()
            else:
                acton.status = Status(name=oform.cleaned_data['status']).put()
            
            acton.slug = "-".join(re.findall("\w+", acton.title)).lower()
            

            
            
            
            
            post=Post()
            post.poster=scuser
            post.content=message+message2
            post.acton=acton.key()
            post.deleted=True
            post.put()
            
            acton_id = acton.put().id()
            return HttpResponseRedirect(reverse('sanjhachoolha.views.show',
                                                 kwargs= {'slug': acton.slug,
                                                          'acton_id':acton_id,
                                                        }
                                                 ))

    else:
        
        
            
        dict={
                 'coordinators':coordinators,
                 'skills':skills,
                 'tags': tags,
                 'category':categories,
                 'priority':acton.priority.name.lower(),
                 'status':acton.status.name.lower()
                 }
        
        eform = Form2(instance=acton)
        oform= Form1(initial=dict) # An unbound form
        
    
    
    sign_out=users.create_logout_url(reverse(signout_view, kwargs={'acton_id':acton_id}))#wether to allow signout must be views'decision 
    return shortcuts.render_to_response('sc-actonedit.html', {'eform': eform,
                                                              'oform':oform,
                                                              'acton_id':acton_id,
                                                              'foo':sign_out, 
                                                              'user_':user_,
                                                              'login_message':"Sign out"                                                              
                                                            })
        
    
#note - to sign up is to actually work on an acton. To subscribe is to simply follow  
def subscribe(request, acton_id):
    """subscribes user to an acton. Currently i don't verify if user is signed in or not
    If he isn't then weirdos"""
    
    if request.method=='POST':
        user_=users.get_current_user()
        acton = Acton.get_by_id(int(acton_id)) 
        
        scuser=request.POST['pdata']
        if scuser != "None":
            scuser=db.Key(scuser)
                    
            if scuser not in acton.subscribers:
                acton.subscribers.append(scuser)
            acton.put()
            
            message = mail.EmailMessage(sender="animesh@gmail.com",
                                         subject="Confirmation of subscription")
            message.to = user_.email()
            message.body = """
            Dear %s:
            
            You have successfully subscribed to Acton %s titled: %s.
             You will now be able to receive updates right in your doorstep
            
            Please let us know if you have any questions.
            
            The Sanjhachoolha Team
            """ % (user_.nickname(), acton_id, acton.title)
            message.send()
            return HttpResponseRedirect(reverse('sanjhachoolha.views.show',
                                                     kwargs= {'slug': acton.slug,
                                                              'acton_id':acton_id,
                                                            }
                                                 ))       

def unsubscribe(request, acton_id):
    """unsubscribes user from an acton.Once again no check if user is signed in"""
    if request.method=='POST':
        user_=users.get_current_user()
        acton = Acton.get_by_id(int(acton_id)) 
        
        scuser=request.POST['pdata']
        if scuser != "None":
            scuser=db.Key(scuser)
                    
            if scuser in acton.subscribers:
                acton.subscribers.remove(scuser)
                acton.put()
            
            message = mail.EmailMessage(sender="animesh@gmail.com",
                                         subject="Confirmation of subscription")
            message.to = user_.email()
            message.body = """
            Dear %s:
            
            You have decided to unsubscribe from  %s titled: %s.
             You will not be able to receive updates from now on
                
            Please let us know if you have any questions.
            
            The Sanjhachoolha Team
            """ % (user_.nickname(), acton_id, acton.title)
            message.send()
            return HttpResponseRedirect(reverse('sanjhachoolha.views.show',
                                                     kwargs= {'slug': acton.slug,
                                                              'acton_id':acton_id,
                                                            }
                                                 ))

def signup(request, acton_id):
    """signup user to work for an acton"""
    signin_view="sanjhachoolha.views.signup"
    signout_view="sanjhachoolha.views.show"
    ##put the code block below in a function
    scuser=None
    user_ = users.get_current_user()
    if user_:
        var= SCUser.gql("WHERE email_id = :1", user_.email().lower()).get()
        if var:
            scuser=var.key()
        else:
            scuser=SCUser(user=user_, email_id=user_.email().lower()).put()
    else:
        
        sign_in = users.create_login_url(reverse(signin_view, kwargs={'acton_id':acton_id,
                                                                      }))
        return shortcuts.render_to_response("sc-login.html", {'foo': sign_in,
                                                              'login_message':"Sign in"})
    
    
    if request.method=='POST':
        aform = FormActor(request.POST)
        if aform.is_valid():
            post=Post()
            post.acton=db.Key.from_path(Acton.kind(), int(acton_id))
            post.poster=scuser
            post.content="MY Skills: %s<br />How I'll help: %s<br />More: %s" % (aform.cleaned_data['skills'],
                                                                         aform.cleaned_data['how'],
                                                                         aform.cleaned_data['more'],)
            post.put()
            acton = Acton.get_by_id(int(acton_id))
            acton.actors.append(scuser)
            acton.put()   
            
            coordinators=[]
            for coordinatorKey in acton.coordinators:
                coordinator = SCUser.get(coordinatorKey)
                coordinators.append(coordinator.email_id)
            creator=acton.creator
            coordinators.append(creator.email_id)
            
            message = mail.EmailMessage(sender="animesh@gmail.com",
                                         subject="confirmation of signup to acton: %s" % acton.title )
            message.to = user_.email()
            message.cc=coordinators
            message.body = """
            Dear %s:
            
            We are joyed to see you join our cause ( Acton  %s titled: %s.)
            With you signing up, you will now be able to receive updates right in your mailbox     
            A comment has been posted on your behalf in the relevant acton thread informing others of your decision to help us.
                
            Please let us know if you have any questions.
            
            The Sanjhachoolha Team
            """ % (user_.nickname(), acton_id, acton.title)
            message.send()
            
            
            
            return HttpResponseRedirect(reverse('sanjhachoolha.views.show',
                                                 kwargs= {'slug': "signed-up",
                                                          'acton_id':acton_id,
                                                        }
                                                 ))
    aform=FormActor()
    sign_out=users.create_logout_url(reverse(signout_view, kwargs={'acton_id':acton_id,
                                                                      'slug':"signed-out",}))
    
    return shortcuts.render_to_response("sc-actor.html", {'aform':aform,
                                                          'foo':sign_out,
                                                          'login_message':"Sign in",
                                                          'user_':user_,
                                                          'acton_id':acton_id,
                                                          })   

def leave(request, acton_id):
    """allows user to stop working on an acton"""
    if request.method=='POST':
        user_=users.get_current_user()
        acton = Acton.get_by_id(int(acton_id)) 
        
        scuser=request.POST['pdata']
        if scuser != "None":
            scuser=db.Key(scuser)
                    
            if scuser in acton.actors:
                acton.actors.remove(scuser)
                acton.put()
                post=Post()
                post.poster=scuser
                post.content="%s has left this acton on %2s" % (user_.nickname(), datetime.datetime.now())
                post.acton=db.Key.from_path(Acton.kind(), int(acton_id))
                post.put()
            
            message = mail.EmailMessage(sender="animesh@gmail.com",
                                         subject="Confirmation of leaving")
            message.to = user_.email()
            message.body = """
            Dear %s:
            
            You have decided to Stop working on Acton  %s titled: %s.
             You will not be able to receive updates from now on. A message has been posted on 
             your behalf in the relevant acton thread informing them of your decision.
                
            Please let us know if you have any questions.
            
            The Sanjhachoolha Team
            """ % (user_.nickname(), acton_id, acton.title)
            message.send()
            return HttpResponseRedirect(reverse('sanjhachoolha.views.show',
                                                     kwargs= {'slug': acton.slug,
                                                              'acton_id':acton_id,
                                                            }
                                                 ))

def add_comment(request, acton_id):
    """add a new comment"""
    signin_view="sanjhachoolha.views.show"
    signout_view="sanjhachoolha.views.show"
    ##put the code block below in a function
    scuser=None
    user_ = users.get_current_user()
    if user_:
        var= SCUser.gql("WHERE email_id = :1", user_.email().lower()).get()
        if var:
            scuser=var.key()
        else:
            scuser=SCUser(user=user_, email_id=user_.email()).put()

    else:
        sign_in = users.create_login_url(reverse(signin_view, kwargs={'acton_id':int(acton_id),
                                                                      'slug':"hmm"}))
        return shortcuts.render_to_response("sc-login.html", {'foo': sign_in,
                                                              'login_message':"Sign in"})

    
    
    if request.method == 'POST':
        pform= FormPost(request.POST)
        if pform.is_valid():
            post=pform.save(commit=False)
            post.acton=db.Key.from_path(Acton.kind(), int(acton_id))
            post.poster=scuser
            post.deleted=False
            post.put()
            
    return HttpResponseRedirect(reverse('sanjhachoolha.views.show',
                                                 kwargs= {'slug': "success",
                                                          'acton_id':int(acton_id),
                                                        }
                                                 ))
 
def delete_comment(request, acton_id, comment_id):
    """add a new comment"""
    if request.method=='POST':
           
        var=db.Key.from_path(Post.kind(), int(comment_id))
        post=Post.get(var)
        email_id=request.POST['pdata'].lower()
        
        if (email_id==post.poster.email_id or email_id==post.acton.creator.email_id):
            post.content="This post was deleted on %s by %s" % (datetime.datetime.now(), post.poster.user.nickname())
            post.deleted=True
            post.put()
            
            return HttpResponseRedirect(reverse('sanjhachoolha.views.show',
                                                 kwargs= {'slug': "deleted",
                                                          'acton_id':int(acton_id),
                                                        }
                                                 ))
def GetAuthSubUrl(acton_id=None):
  next = "http://localhost:8080%s" % reverse("sanjhachoolha.views.addreminder", kwargs={'acton_id':acton_id})
  scope = 'http://www.google.com/calendar/feeds/'
  secure = False
  session = True
  calendar_service = gdata.calendar.service.CalendarService()
  gdata.alt.appengine.run_on_appengine(calendar_service)
  return calendar_service.GenerateAuthSubURL(next, scope, secure, session);

def addreminder(request, acton_id):
    """subscribes user to an acton. Currently i don't verify if user is signed in or not
    If he isn't then weirdos"""
    calendar_service = gdata.calendar.service.CalendarService()
    gdata.alt.appengine.run_on_appengine(calendar_service)
    session_token = None
    auth_token = gdata.auth.extract_auth_sub_token_from_url(request.get_full_path())
    if auth_token:
      session_token = calendar_service.upgrade_to_session_token(auth_token)
    if session_token and users.get_current_user():
      calendar_service.token_store.add_token(session_token)
    elif session_token:
      calendar_service.current_token = session_token

    authSubUrl = GetAuthSubUrl(acton_id);
    feed=None
    if session_token:
        feed = calendar_service.GetAllCalendarsFeed()
        event = gdata.calendar.CalendarEventEntry()
        event.title = atom.Title(text="entry")
        event.content = atom.Content(text="contender")
        event.where.append(gdata.calendar.Where(value_string="at school"))
        start_time=None
        end_time=None
    
        if start_time is None:
          # Use current time for the start_time and have the event last 1 hour
          start_time = time.strftime('%Y-%m-%dT%H:%M:%S.000Z', time.gmtime())
          end_time = time.strftime('%Y-%m-%dT%H:%M:%S.000Z', time.gmtime(time.time() + 3600))
        event.when.append(gdata.calendar.When(start_time=start_time, end_time=end_time))
        
        new_event = calendar_service.InsertEvent(event, '/calendar/feeds/default/private/full')
        
               
    
    return shortcuts.render_to_response('sc-blah.html', {'authSubUrl':authSubUrl,
                                                         'feed':feed,})
    


def search(request):
  responseText = "Hello, world. This shows the main search page."
  return respond(request, None, 'sc-base', {'content': responseText})
  
def listall(request, last_id=None):
    """show list of all actons"""
    k=2
    acton_list=[]
    if last_id:
        last_key=db.Key.from_path(Acton.kind(), int(last_id))
        acton_list= Acton.gql("WHERE __key__<= :1 order by __key__ desc", last_key).fetch(k+1)
    else:
        acton_list = Acton.gql("ORDER BY __key__ desc").fetch(k+1)
    end=None
    if acton_list:
        
        end=acton_list[-1].key()
        end=end.id()
        if len(acton_list)<k+1:
            end=None
        else:
            del acton_list[-1]
    return shortcuts.render_to_response("sc-listall.html", {'acton_list':acton_list,
                                                              'end':end
                                                       })

def showuser(request, user_id):
    """ show a particular user with id. eg /sanjhachoolha/users/22 """
    sign_out=users.create_logout_url(reverse("sanjhachoolha.views.showuser", kwargs={'user_id':user_id,}))
    
    cuser=users.get_current_user()
    cuser=SCUser.gql("WHERE email_id=:1", cuser.email().lower()).get()
    if cuser.role=='Admin' or users.is_current_user_admin():
        var=True
    else:
        var=False
    
    scuser=SCUser.get_by_id(int(user_id))
    if scuser and cuser:            
        return shortcuts.render_to_response("sc-profile.html", {'foo':sign_out,
                                                                'login_message':"Sign out",
                                                                'user_':cuser.user,
                                                                'var':var,
                                                                
                                                                'scuser':scuser})

    
    
    
def setactoncreator(request, user_id):
    """ /sc/users/22/setactoncreator POST only"""
    if request.method=='POST':
        scuser=request.POST['pdata']
        if scuser !="None":
            scuser=db.Key(scuser)
            scuser=SCUser.get(scuser)
            scuser.role="ActonCreator"
            scuser.put()
            
            message = mail.EmailMessage(sender="animesh@gmail.com",
                                         subject="congrats! you now have acton creation priveleges")
            message.to = scuser.email_id
            message.body = """
            Dear %s:
            Thanks for your interest in this noble cause. It gives us pleasure to grant you
            The privelege of creating Actons.
            "Every Acton counts"
                            
            Please let us know if you have any questions.
            
            The Sanjhachoolha Team
            """ % (scuser.user.nickname())
            message.send()
            return HttpResponseRedirect(reverse('sanjhachoolha.views.showuser',
                                                     kwargs= {
                                                              'user_id':user_id,
                                                            }
                                                 ))

        
        
    
def unsetactoncreator(request, user_id):
    """ /sc/users/22/unsetactoncreator """
    if request.method=='POST':
        scuser=request.POST['pdata']
        if scuser !="None":
            scuser=db.Key(scuser)
            scuser=SCUser.get(scuser)
            scuser.role="None"
            scuser.put()
            
            message = mail.EmailMessage(sender="animesh@gmail.com",
                                         subject="congrats! you now have acton creation priveleges")
            message.to = scuser.email_id
            message.body = """
            Dear %s:
            ActonCreation Priveleges have been revoked. 
                            
            Please let us know if you have any questions.
            
            The Sanjhachoolha Team
            """ % (scuser.user.nickname())
            message.send()
            return HttpResponseRedirect(reverse('sanjhachoolha.views.showuser',
                                                     kwargs= {
                                                              'user_id':user_id,
                                                            }
                                                 ))
def listusers(request, last_id=None):
    signin_view="sanjhachoolha.views.listusers"
    signout_view="sanjhachoolha.views.index"
    ##put the code block below in a function
    
    user_ = users.get_current_user()
    sign_in = users.create_login_url(reverse(signin_view, kwargs={'last_id':last_id}))
    if user_:
        var= SCUser.gql("WHERE email_id = :1", user_.email().lower()).get()
        if not var:
            
            var2 = user_.email()
            var2 = var2.lower()
            scuser=SCUser(user=user_, email_id = var2).put()
    else:
        
        return shortcuts.render_to_response("sc-login.html", {'foo': sign_in,
                                                              'login_message':"Sign in"})
    
    
    k=2
    user_list=[]
    if last_id:
        last_key=db.Key.from_path(SCUser.kind(), int(last_id))
        user_list= SCUser.gql("WHERE __key__<= :1 order by __key__ desc", last_key).fetch(k+1)
    else:
        user_list = SCUser.gql("ORDER BY __key__ desc").fetch(k+1)
    end=None
    if user_list:
        
        end=user_list[-1].key()
        end=end.id()
        if len(user_list)<k+1:
            end=None
        else:
            del user_list[-1]
    sign_out=users.create_logout_url(reverse(signout_view))
    return shortcuts.render_to_response("sc-listusers.html", {'user_list':user_list,
                                                              'end':end,
                                                              'foo':sign_out,
                                                              'user_':user_,
                                                              'login_message':"Sign out",

                                                       })
    
def category(request):
    #i guess no authentication to view categories and actons
    last_id=None
    if request.GET and request.GET['last_id']:
        last_id = request.GET['last_id']
    k=2
    category_list=[]
    if last_id:
        last_key=db.Key.from_path(Category.kind(), int(last_id))
        category_list= Category.gql("WHERE __key__<= :1 order by __key__ desc", last_key).fetch(k+1)
    else:
        category_list = Category.gql("ORDER BY __key__ desc").fetch(k+1)
    end=None
    if category_list:
        
        end=category_list[-1].key()
        end=end.id()
        if len(category_list)<k+1:
            end=None
        else:
            del category_list[-1]
    
    return shortcuts.render_to_response("sc-listcategory.html", {'category_list':category_list,
                                                              'end':end,
                                                             

                                                       })
    
def categoryName(request, categoryName=None):
    
    category = Category.gql("where name = :1", categoryName).get()
    category_key = category.key()
    
    last_id=None
    if request.GET and request.GET['last_id']:
        last_id = request.GET['last_id']
    k=2
    acton_list=[]
    if last_id:
        last_key=db.Key.from_path(Acton.kind(), int(last_id))
        acton_list = Acton.gql("WHERE __key__<= :1 and category = :2 order by __key__ desc", last_key, category_key).fetch(k+1)
    else:
        acton_list = Acton.gql("where category = :1 ORDER BY __key__ desc", category_key).fetch(k+1)
    end=None
    if acton_list:
        
        end=acton_list[-1].key()
        end=end.id()
        if len(acton_list)<k+1:
            end=None
        else:
            del acton_list[-1]
    
    return shortcuts.render_to_response("sc-listall.html", {'acton_list':acton_list,
                                                              'end':end,
                                                              })
    
def tag(request):
    #i guess no authentication to view categories and actons
    last_id=None
    if request.GET and request.GET['last_id']:
        last_id = request.GET['last_id']
    k=2
    tag_list=[]
    if last_id:
        last_key=db.Key.from_path(Tag.kind(), int(last_id))
        tag_list= Tags.gql("WHERE __key__<= :1 order by __key__ desc", last_key).fetch(k+1)
    else:
        tag_list = Tags.gql("ORDER BY __key__ desc").fetch(k+1)
    end=None
    if tag_list:
        
        end=tag_list[-1].key()
        end=end.id()
        if len(tag_list)<k+1:
            end=None
        else:
            del tag_list[-1]
    
    return shortcuts.render_to_response("sc-listtag.html", {'tag_list':tag_list,
                                                              'end':end,
                                                             

                                                       })    

def tagName(request, tagName=None):
    
    tag = Tags.gql("where name = :1", tagName).get()
    tag_key = tag.key()
    
    last_id=None
    if request.GET and request.GET['last_id']:
        last_id = request.GET['last_id']
    k=2
    acton_list=[]
    if last_id:
        last_key=db.Key.from_path(Acton.kind(), int(last_id))
        acton_list = Acton.gql("WHERE __key__<= :1 and tags = :2 order by __key__ desc", last_key, tag_key).fetch(k+1)
    else:
        acton_list = Acton.gql("where tags = :1 ORDER BY __key__ desc", tag_key).fetch(k+1)
    end=None
    if acton_list:
        
        end=acton_list[-1].key()
        end=end.id()
        if len(acton_list)<k+1:
            end=None
        else:
            del acton_list[-1]
    
    return shortcuts.render_to_response("sc-listall.html", {'acton_list':acton_list,
                                                              'end':end,
                                                              })    
class LatestEntries(Feed):
    def get_object(self, bits):
        # In case of "/rss/beats/0613/foo/bar/baz/", or other such clutter,
        # check that bits has only one member.
        if len(bits) != 1:
            raise ObjectDoesNotExist
        return Acton.gql("Where __key__=:1", db.Key.from_path(Acton.kind(), int(bits[0]))).get()

    def title(self, obj):
        return "Sanjhachoolha: updates on Acton: %s" % obj.title

    def link(self, obj):
        if not obj:
            raise FeedDoesNotExist
        return reverse('sanjhachoolha.views.show', kwargs={'acton_id':obj.key().id(), 'slug':obj.slug})

    def description(self, obj):
        return "Changes to acton: %s" % obj.title

    def items(self, obj):
       return obj.post_set.order('-timestamp').fetch(5)
#       return Crime.objects.filter(beat__id__exact=obj.id).order_by('-crime_date')[:30]
    def item_link(self, item):
        return reverse('sanjhachoolha.views.show', kwargs={'acton_id':item.acton.key().id(),
                                                            'slug':item.acton.slug})
